package apigateway.project.core.filter.flow.flowforInstance;

import apigateway.project.commen.config.ServiceInstance;
import apigateway.project.commen.constant.FilterConst;
import apigateway.project.commen.enums.ResponseCode;
import apigateway.project.commen.exception.NotFoundException;
import apigateway.project.core.CacheConfig;
import apigateway.project.core.aspect.FilterAspect;
import apigateway.project.core.aspect.Order;
import apigateway.project.core.context.GlobalContext;
import apigateway.project.core.filter.Filter;

import java.util.Set;

@FilterAspect(value = FilterConst.FLOW_FILTER_ID_INSTANCE,name = FilterConst.FLOW_FILTER_NAME_INSTANCE)
@Order(FilterConst.FLOW_FILTER_ORDER_INSTANCE)
public class FlowFilterByInstance implements Filter {
    @Override
    public void doFilter(GlobalContext ctx) throws Exception {
        int instanceNumber = getInstanceNumber(ctx);
        /**
         * 若没有实例，扔出异常
         */
        //TODO 后续需要在netty的Handler里面对这个异常进行捕捉和具体的处理
        if (instanceNumber == 0) {
            throw new NotFoundException(ResponseCode.SERVICE_INSTANCE_NOT_FOUND);
        }
        GatewayFlowControlRuleForInstance flowControlByInstanceRule = new FlowControlByInstanceRule(ctx,instanceNumber,ctx.getRule().getServiceName());
        flowControlByInstanceRule.doFilterControlFilter();
    }

    /**
     * 获取具体的服务数量
     * @param ctx
     * @return
     */
    public int getInstanceNumber(GlobalContext ctx) {
        Set<ServiceInstance> serviceByServiceName = CacheConfig.getCacheConfig().getServiceByServiceName(ctx.getRule().getServiceName());
        return serviceByServiceName.size();
    }



}
